﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using AltiComLib;

public class Dialer {
	public class OnHookException : Exception {
		public OnHookException() : base("Take your phone off-hook and try again.") { }
		public OnHookException(string Message) : base(Message) { }
	}
	static System.Web.Caching.Cache Cache { get { return HttpContext.Current.Cache; } }
	static System.Security.Principal.IPrincipal User { get { return HttpContext.Current.User; } }
	string _ext = "2190";
	string Extention { get { return _ext; } set { _ext = value; } }
	string _pwd = "1029";
	string Password { get { return _pwd; } set { _pwd = value; } }
	string _num = "73054667786";
	string DialNumber {
		get { return _num; }
		set {
			_num = value;
			_num = Regex.Replace(_num, "[^0-9]", "").Trim();
			if (_num.Length > 5 && !_num.StartsWith("1")) _num = "1" + _num;
			if (_num.Length > 5) _num = "7" + _num;
		}
	}

	string KEY_ACCESS = "ALT.Access."+ User.Identity.Name;
	AAccess aAccess {
		get {
			try {
				if (Cache[KEY_ACCESS ] == null)
					Cache.Insert(KEY_ACCESS,
						new AAccess(),
						null, System.Web.Caching.Cache.NoAbsoluteExpiration,
						new TimeSpan(0, 0, 3), System.Web.Caching.CacheItemPriority.NotRemovable, RemCallBack);
				AAccess a = Cache[KEY_ACCESS] as AAccess;

				if (!a.IsConnected) a.Connect("192.168.6.7");
				return a;
			} catch (Exception exc) {
				throw new Dimok.Exceptions.ASPException("AltiGen:Connect", exc);
			}
		}
	}
	bool NeedLogin = true;
	string KEY_SESSION = "ALT.Session." + User.Identity.Name;
	ASessionClass aSession {
		get {
			try {
				if (Cache[KEY_SESSION] == null ) {
					Cache.Insert(KEY_SESSION,
						aAccess.Logon(Extention, Password, A_LOGON_TYPE.A_LOGON_TYPE_EXT),
						null, System.Web.Caching.Cache.NoAbsoluteExpiration,
						new TimeSpan(0, 0, 2), System.Web.Caching.CacheItemPriority.NotRemovable, RemCallBack);
					if (Cache[KEY_SESSION] == null) throw new Exception("Logon Failed.");
				}
				return Cache[KEY_SESSION] as ASessionClass;
			} catch (Exception exc) {
				throw new Dimok.Exceptions.ASPException(exc, "AltiGen:Connect", "", "Ext", Extention);
			}
		}
	}
	System.Web.Caching.CacheItemRemovedCallback RemCallBack = null;
	void RemovedCallback(String k, Object v, System.Web.Caching.CacheItemRemovedReason r) {
		if (typeof(AAccess).IsInstanceOfType(v) ) ((AAccess)v).Disconnect();
		if (typeof(ASessionClass).IsInstanceOfType(v))((ASessionClass)v).Dispose();
		v = null;
	}

	string KEY_CALL_CONTROL = "ALT.CallControl." + User.Identity.Name;
	IACallControl callControl {
		get {
			try {
				if (Cache[KEY_CALL_CONTROL] == null) {
					Cache.Insert(KEY_CALL_CONTROL,
						aSession.GetServiceObj(A_SERVICE_TYPE.A_SERVICE_CALLCONTROL),
						null, System.Web.Caching.Cache.NoAbsoluteExpiration,
						new TimeSpan(0, 0, 1), System.Web.Caching.CacheItemPriority.NotRemovable, RemCallBack);
					if (Cache[KEY_CALL_CONTROL] == null) throw new Exception("Get Call Control failed.");
				}
				return Cache[KEY_CALL_CONTROL] as IACallControl;
			} catch (Exception exc) {
				throw new Dimok.Exceptions.ASPException(exc, "AltiGen:Connect", aSession.MyLineNum);
			}
		}
	}
	//				m_obCallControl = (IACallControl)m_obSession.GetServiceObj(AltiComLib.A_SERVICE_TYPE.A_SERVICE_CALLCONTROL);

	public Dialer(string Extention, string Password):this(Extention,Password,"") {}
	public Dialer(string Extention, string Password, string DialNumber) {
		this.Extention = Extention;
		this.Password = Password;
		this.DialNumber = DialNumber;
		RemCallBack = new System.Web.Caching.CacheItemRemovedCallback(RemovedCallback);
		CleanSession();
	}
	public void OnHook() {
		try {
			callControl.SimOnHook();
		} finally {
			CleanSession();
		}
	}
	public void Dial() {
		IACallControl cc = callControl;
		try {
			if (aSession.MyLine.State != A_LINE_STATE.A_LINE_STATE_OFFHOOK && aSession.MyLine.State != A_LINE_STATE.A_LINE_STATE_IDLE)
				throw new Exception("Status " + aSession.MyLine.State + " is not supported.");
			if (aSession.MyLine.State == A_LINE_STATE.A_LINE_STATE_IDLE) {
				cc.Ring();
				throw new OnHookException("onhook");
			}
			try {
				cc.Dial(DialNumber);
			} catch (Exception exc) {
				throw new Dimok.Exceptions.ASPException(exc, "AltiGen:Connect", "", "Number", DialNumber);
			}
		} finally {
			CleanSession();
		}
	}
	void CleanSession() {
		return;
		Cache.Remove(KEY_CALL_CONTROL);
		if (Cache[KEY_SESSION] != null) {
			((ASessionClass)Cache[KEY_SESSION]).Dispose();
			Cache.Remove(KEY_SESSION);
		}
		if (Cache[KEY_ACCESS] != null) {
			((AAccess)Cache[KEY_ACCESS]).Disconnect();
			Cache.Remove(KEY_ACCESS);
		}
	}
}
